import { ref, onMounted, onUnmounted } from 'vue'

export function useDraggable(elementRef, options = {}) {
  const position = ref(options.initialPosition || { x: 0, y: 0 })
  const isDragging = ref(false)
  const startPos = ref({ x: 0, y: 0 })

  const onMouseDown = (e) => {
    if (e.button !== 0) return // 只响应左键
    if (options.dragHandle && !e.target.closest(options.dragHandle)) return

    isDragging.value = true
    startPos.value = {
      x: e.clientX - position.value.x,
      y: e.clientY - position.value.y
    }

    document.addEventListener('mousemove', onMouseMove)
    document.addEventListener('mouseup', onMouseUp)
    e.stopPropagation()
  }

  const onMouseMove = (e) => {
    if (!isDragging.value) return

    position.value = {
      x: e.clientX - startPos.value.x,
      y: e.clientY - startPos.value.y
    }

    // 限制在窗口范围内
    if (options.boundary) {
      const { width, height } = elementRef.value.getBoundingClientRect()
      position.value.x = Math.max(0, Math.min(window.innerWidth - width, position.value.x))
      position.value.y = Math.max(0, Math.min(window.innerHeight - height, position.value.y))
    }
  }

  const onMouseUp = () => {
    isDragging.value = false
    document.removeEventListener('mousemove', onMouseMove)
    document.removeEventListener('mouseup', onMouseUp)

    if (options.onDragEnd) {
      options.onDragEnd(position.value)
    }
  }

  onMounted(() => {
    const el = elementRef.value
    if (!el) return

    el.addEventListener('mousedown', onMouseDown)
    el.style.position = 'absolute'
    el.style.left = `${position.value.x}px`
    el.style.top = `${position.value.y}px`
  })

  onUnmounted(() => {
    const el = elementRef.value
    if (!el) return

    el.removeEventListener('mousedown', onMouseDown)
    document.removeEventListener('mousemove', onMouseMove)
    document.removeEventListener('mouseup', onMouseUp)
  })

  return {
    position,
    isDragging
  }
}
